package com.pi.shisan.web.controller;

import com.pi.shisan.service.audio.AudioLevelManager;
import com.pi.shisan.service.audio.AudioPlayer;
import com.pi.shisan.service.audio.MixPlayer;
import com.pi.shisan.service.audio.MultiFilePlayer;
import com.pi.shisan.service.dto.AudioInfoDTO;
import com.pi.shisan.service.dto.PlayerInfo;
import com.pi.shisan.service.dto.Result;
import com.pi.shisan.service.schedule.LoadingComponent;
import com.pi.shisan.service.util.ComponentManager;
import com.pi.shisan.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

@RestController
@RequestMapping("/music")
public class MusicListController {

    @Autowired
    private AudioLevelManager audioLevelManager;

    @Autowired
    private ComponentManager componentManager;

    @Autowired
    private Consumer<Integer> playBeforeVolume;

    private final static Comparator<AudioInfoDTO> NAME_SORT = (a1,a2)->{
        if (a1.getAudioName() == null) {
            return 1;
        }
        if (a2.getAudioName() == null) {
            return -1;
        }
        return a1.getAudioName().compareTo(a2.getAudioName());
    };

    @GetMapping("/list")
    public Result<List<AudioInfoDTO>> musicList() {
        File[] files = new File("music").listFiles();
        if (files == null) {
            return Result.ok(Collections.EMPTY_LIST);
        }
        List<AudioInfoDTO> musicDTOS = new ArrayList<>(files.length);
        for (File f : files) {
            if (f.isDirectory()) {
                continue;
            }
            AudioInfoDTO ms = new AudioInfoDTO();
            ms.setAudioName(FileUtils.getFileNameWithoutSuffix(f.getName()));
            ms.setSuffix(FileUtils.getFileNameSuffix(f.getName()));
            ms.setAudioPath(f.getPath());
            musicDTOS.add(ms);
        }
        musicDTOS.sort(NAME_SORT);
        return Result.ok(musicDTOS);
    }

    @GetMapping("/current")
    public Result<PlayerInfo> currentPlayer() {
        AudioLevelManager.AudioMixerEntity currentMixPlayer = audioLevelManager.getCurrentMixPlayer();
        if (currentMixPlayer != null) {
            //2 闹铃 3 音乐播放器
            //1 整点报时 4 空播放器
            if (currentMixPlayer.getLevel() != 2 && currentMixPlayer.getLevel() != 3) {
                return Result.ok();
            }
            AudioLevelManager.AudioMixer audioMixer = currentMixPlayer.getAudioMixer();
            if (audioMixer != null) {
                if (audioMixer instanceof AudioPlayer){
                    AudioPlayer audioPlayer = (AudioPlayer) audioMixer;
                    if (audioPlayer.isDestroy()) {
                        return Result.ok();
                    }
                    PlayerInfo playerInfo = new PlayerInfo();
                    playerInfo.setLevel(currentMixPlayer.getLevel());
                    if (audioMixer instanceof MultiFilePlayer) {
                        MultiFilePlayer.RepeatTimesConfig currentPlayFile = ((MultiFilePlayer) audioMixer).getCurrentPlayFile();
                        if (currentPlayFile != null) {
                            playerInfo.setName(currentPlayFile.getDes());
                        }
                    } else {
                        playerInfo.setName(FileUtils.getFileNameWithoutSuffix(audioPlayer.getAudioFile().getName()));
                    }
                    return Result.ok(playerInfo);
                }

            }
        }
        return Result.ok();
    }

    /**
     * 关闭当前的播放器
     * @param level
     * @return
     */
    @GetMapping("/close/{level}")
    public Result<Void> closeCurrent(@PathVariable("level") Integer level) {
        AudioLevelManager.AudioMixerEntity currentMixPlayer = audioLevelManager.getCurrentMixPlayer();
        if (currentMixPlayer != null && Objects.equals(currentMixPlayer.getLevel(), level)) {
            currentMixPlayer.destroy();
        }
        return Result.ok();
    }

    @PostMapping("/play")
    public Result<Void> playMusic(@RequestBody AudioInfoDTO audioInfoDTO) throws Exception{
        if (audioInfoDTO.getAudioPath() == null) {
            return null;
        }
        if (!LoadingComponent.isOver()) {
            return Result.err("稍等，仍在启动中");
        }
        File file = new File(audioInfoDTO.getAudioPath());
        AudioPlayer audioPlayer = new MixPlayer(file, componentManager::showMusicEffect);
        audioPlayer.setTitle(FileUtils.getFileNameWithoutSuffix(file.getName()));
        audioPlayer.setPlayBeforeVolume(playBeforeVolume);
        audioLevelManager.playMixer(audioPlayer,3);
        return Result.ok();
    }
}
